package com.ych.modules.base.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ych.redis.config.RedisKeyConfig;
import com.ych.modules.base.dbEntity.TUserTokenEntity;
import com.ych.modules.base.mapper.TUserTokenMapper;
import com.ych.modules.base.service.ITUserTokenService;
import com.ych.utils.token.TokenGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/5
 * Time: 15:10
 * Description:
 */
@Service("ITUserTokenService")
public class TUserTokenServiceImpl extends ServiceImpl<TUserTokenMapper, TUserTokenEntity> implements ITUserTokenService {
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TUserTokenEntity createToken(String userId) {
        boolean ok;
        //生成一个token
        String token = TokenGenerator.generateValue();
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + RedisKeyConfig.expireTime * 1000);
        //判断是否生成过token
        TUserTokenEntity tokenEntity = this.selectById(userId);
        if (tokenEntity == null) {
            tokenEntity = new TUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            tokenEntity.setCreateTime(new Date());
            //保存token
            ok = this.insert(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //更新token
            ok = this.updateById(tokenEntity);
        }
        if (!ok) {
            return null;
        }
        return tokenEntity;
    }

    @Override
    public TUserTokenEntity queryByToken(String accessToken) {
        Wrapper<TUserTokenEntity> wrapper = new EntityWrapper<TUserTokenEntity>()
                .where("1=1")
                .eq("token", accessToken);
        TUserTokenEntity tokenEntity = this.selectOne(wrapper);
        return tokenEntity;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void logout(String userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();
        //修改token
        TUserTokenEntity tokenEntity = new TUserTokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        this.updateById(tokenEntity);
    }
}